home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8386 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  74 lines

  1. Path: piglet.cc.utexas.edu!not-for-mail
  2. From: lucien@ccwf.cc.utexas.edu
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Memory allocation.
  5. Date: 17 Feb 1996 10:56:00 -0600
  6. Organization: The University of Texas at Austin
  7. Message-ID: <4g51b0$bnn@piglet.cc.utexas.edu>
  8. References: <1996Feb10.161530.26449@wisipc.weizmann.ac.il>
  9. NNTP-Posting-Host: piglet.cc.utexas.edu
  10.  
  11. In article <1996Feb10.161530.26449@wisipc.weizmann.ac.il>,
  12. Kajdan Dimitry  <cerlpvk> wrote:
  13. >I'm a starter so the question may seem stupid.
  14.  
  15. Not at all. I'm still a beginner to c++, so this was a good exercise
  16. for me too.
  17. 8-)
  18.  
  19. >
  20. >Would someone explain why this program works?
  21. >
  22. >int* func()
  23. >{
  24. >  
  25. >  
  26. > int b[10];
  27. >   for(int i=0;i<9;i++)
  28. >     b[i]=i;
  29. >  return b;  
  30. >}
  31.  
  32. The fact that this particular function works is fortuitous. The problem is 
  33. that it returns a pointer to an array that is declared local to the 
  34. function. When the function returns, b[10] goes out of scope, and the
  35. memory that was allocated for it is freed. So, the pointer returned by
  36. func() doesn't point to a valid address anymore.
  37. (I did not figure this out on my own - I gleaned this from another reply
  38. to your post, and from a warning given me by my compiler when I compiled
  39. this. Wish I could claim that i had, though 8-)).
  40.  
  41. >
  42. >int main(){
  43. >  
  44. > int* x= func();
  45.  
  46. Here, x points to a memory location that no longer belongs to b[10] in
  47. func().
  48.  
  49. >
  50. >The point is that b is allocated on the stack i.e without "new".
  51.  
  52. Well, when you declare an array as int b[10]; then memory for the array
  53. is automagically allocated for it. you could also declare a pointer to
  54. an array of 10 ints like this:
  55.  
  56. int *b = new int[10];
  57.  
  58. The scoping issues involved here are different, since new lets you allocate
  59. memory on one function and then use or free it in another. memory allocated
  60. with the new operator isn't tied to the lifetime of a function like
  61. automatic variables such as "int b[10];" are.
  62.  
  63. So, return b will return a valid pointer if you declare b this way.
  64.  
  65. Other ways to fix func() are to declare the array globally, or you can
  66. declare it static. In both cases, the array will 'persist' even after it goes
  67. out of scope.
  68.  
  69. Of course, if I'm wrong about any of this, please correct me.
  70. Thanks!
  71.  
  72. Lucien S.
  73.  
  74.